package utils

import (
	"net"
	"os"

	"github.com/gofiber/fiber/v2"
	"github.com/rs/zerolog/log"
)

// GetLocalIP retrieves the local IP address of the machine
func GetLocalIP() string {
    addrs, err := net.InterfaceAddrs()
    if err != nil {
		log.Error().Msgf("net.InterfaceAddrs error: %v", err)
        return ""
    }

    for _, addr := range addrs {
        // Check if the address is not a loopback address and is an IP address
        if ipNet, ok := addr.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
            if ipNet.IP.To4() != nil {
                return ipNet.IP.String()
            }
        }
    }

	log.Warn().Msg("no local IP address found")
    return ""
}

// GetHostname retrieves the local server name (hostname) of the machine
func GetHostname() string {
    hostname, err := os.Hostname()
    if err != nil {
        log.Error().Msgf("os.Hostname error: %v", err)
        return ""
    }
    return hostname
}

func GetRequestIp(c *fiber.Ctx) string {
	ip := c.Request().Header.Peek("X-Real-IP")
	if ip == nil {
		ip = c.Request().Header.Peek("X-Forwarded-For")
	}
	if ip == nil {
		return c.IP()
	}
	return string(ip)
}